package com.mz.mattress.core.voice;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.web.bind.annotation.*;

import java.nio.ByteBuffer;
import java.util.*;

@RestController
@RequestMapping("/vehicle")
public class VehicleDeviceController {

    // 生成开匝命令，常开模式转用
    private String getOpenCmd() {
        byte[] realVoice = getSingleWords("", null); // 语音：欢迎光临
        int voice = 0x01;
        String msg = "欢迎光临";
        byte[] welcomeVoice = sendRealVoice(getWordsByCode((byte) voice, realVoice)); // 语音：欢迎光临
        // 显示屏第一行显示欢迎光临
        byte[] welcomeText = sendLineContent(1, msg);
        String welcomeTextStr = byteToHexString2(welcomeText, 0, welcomeText.length);
        String welcomeVoiceStr = byteToHexString2(welcomeVoice, 0, welcomeVoice.length);
        String sData = Base64.encode(HexStringToByte(welcomeVoiceStr + welcomeTextStr));

        // fullContent：开闸并显示播报
        String cmd = "{\"Response_AlarmInfoPlate\":" +
                "{\"info\":\"ok\"," +
                "\"serialData\":" +
                "[{\"serialChannel\":0," +
                "\"data\":\"" + sData + "\"," +
                "\"dataLen\":" + sData.length() + "}]" +
                "}}";

        return cmd;
    }

    private static byte[] getSingleWords(String word, byte[] odata) {
        try {
            char[] ws = word.toCharArray();
            ByteBuffer bb = ByteBuffer.allocate(100);
            if (odata != null)
                bb.put(odata);
            for (char c : ws) {
//                System.out.println("====c"+c);
                Byte b = singleWorldVoiceMap.get(c);
//                System.out.println("====b"+b);
                if (b != null)
                    bb.put(b);
            }
            bb.flip();
            int len = bb.limit();
            byte[] data = new byte[len];
            bb.get(data, 0, len);
            for (int i = 0; i < data.length; i++) {
                System.out.println("=========data" + data[i]);
            }
            return data;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static byte[] getWordsByCode(int code, byte[] odata) {
        try {
            if ((byte) code == (byte) 0x96) {
                code = (byte) 0x1D;
            } else if ((byte) code == (byte) 0x97) {
                code = (byte) 0x18;
            } else if ((byte) code == (byte) 0x98) {
                code = (byte) 0x82;
            } else if ((byte) code == (byte) 0x9A) {
                code = (byte) 0x1B;
            } else if ((byte) code == (byte) 0xAB) {
                code = (byte) 0x8B;
            } else if ((byte) code == (byte) 0xAA) {
                code = (byte) 0x8C;
            } else if ((byte) code == (byte) 0xAE) {
                code = (byte) 0x89;
            } else if ((byte) code == (byte) 0xB0) {
                code = (byte) 0x2E;
            } else if ((byte) code == (byte) 0xA9) {
                code = (byte) 0x92;
            }
            ByteBuffer bb = ByteBuffer.allocate(100);
            if (odata != null) {
                bb.put(odata);
            }
            bb.put((byte) code);
            bb.flip();
            int len = bb.limit();
            byte[] data = new byte[len];
            bb.get(data, 0, len);
            return data;
        } catch (Exception e) {
            return null;
        }
    }

    private static byte[] sendRealVoice(byte[] vData) {
        byte cmd = (byte) 0xDA;
        byte subCmd = (byte) 0x0;
        return packetData(cmd, subCmd, vData);
    }

    private static String byteToHexString2(byte[] bytes, int offset, int len) {
        StringBuilder sb = new StringBuilder(len);
        for (int i = offset; i < offset + len; i++) {
            if (((int) bytes[i] & 0xff) < 0x10)
                sb.append('0');
            sb.append(Integer.toString((bytes[i] & 0xff), 16));
        }
        return sb.toString();
    }

    private static byte[] HexStringToByte(String hexString) {
        if ((hexString.length() % 2) != 0) {
            throw new IllegalArgumentException("字符长度非偶数，异常");
        }
        byte[] t = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            String m = hexString.substring(i, i + 2);
            t[i / 2] = (byte) Integer.parseInt(m, 16);
        }
        return t;
    }

    private static byte[] sendLineContent(int line, String text) {
        byte cmd = (byte) 0xD5;
        try {
            byte displayLine = (byte) 0x41; // 显示在第几行
            byte disPlayType = (byte) 0x52;
            switch (line) {
                case 1:
                    displayLine = (byte) 0x41;
                    break;
                case 2:
                    displayLine = (byte) 0x42;
                    break;
                case 3:
                    displayLine = (byte) 0x43;
                    break;
                case 4:
                    displayLine = (byte) 0x44;
                    break;
                default:
                    break;
            }
            byte[] cont = text.getBytes("GBK");
            byte[] content = new byte[cont.length + 2];
            content[0] = displayLine;
            content[1] = disPlayType;
            System.arraycopy(cont, 0, content, 2, cont.length);
            return packetData(cmd, (byte) 0x0, content);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 组装数据数组
     * @param cmd    指令类型
     * @param subCmd 指令类型
     * @param data   数组数据
     * @return
     */
    public static byte[] packetData(byte cmd, byte subCmd, byte[] data) {
        ByteBuffer b = ByteBuffer.allocate(256);
        b.put((byte) 0xAA);
        b.put((byte) 0x55);
        b.put((byte) 0x02);
        b.put((byte) 0X80);
        b.put(cmd);
        int len = 0;
        if (data != null)
            len += data.length;
        if (subCmd != (byte) 0x0)
            len += 1;
        b.put((byte) (len >> 8));
        b.put((byte) len);
        if (subCmd != (byte) 0x0)
            b.put(subCmd);
        if (data != null)
            b.put(data);
        return crcData(b);
    }

    public static byte[] crcData(ByteBuffer b) {
        b.put((byte) 0x0);
        b.put((byte) 0x0);
        b.flip();
        int len = b.limit();
        byte[] re = new byte[len + 1];
        b.get(re, 0, len - 1);
        int crcData = calcuteCrc(re, 3, len - 5);
        re[len - 2] = (byte) ((crcData & 0xff00) >> 8);
        re[len - 1] = (byte) ((crcData & 0x00ff));
        re[len] = (byte) 0XAF;

        /*System.out.print("指令内容");
        for (byte r : re) {
            System.out.printf("%02X ", r);
        }
        System.out.println();*/
        return re;
    }

    public static int calcuteCrc(byte[] data, int offset, int len) {
        int[] crcTb = {0x0000, 0x8005, 0x800f, 0x000a, 0x801b,
                0x001e, 0x0014, 0x8011, 0x8033, 0x0036, 0x003c, 0x8039, 0x0028,
                0x802d, 0x8027, 0x0022, 0x8063, 0x0066, 0x006c, 0x8069, 0x0078,
                0x807d, 0x8077, 0x0072, 0x0050, 0x8055, 0x805f, 0x005a, 0x804b,
                0x004e, 0x0044, 0x8041, 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8,
                0x80dd, 0x80d7, 0x00d2, 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb,
                0x00ee, 0x00e4, 0x80e1, 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb,
                0x00be, 0x00b4, 0x80b1, 0x8093, 0x0096, 0x009c, 0x8099, 0x0088,
                0x808d, 0x8087, 0x0082, 0x8183, 0x0186, 0x018c, 0x8189, 0x0198,
                0x819d, 0x8197, 0x0192, 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab,
                0x01ae, 0x01a4, 0x81a1, 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb,
                0x01fe, 0x01f4, 0x81f1, 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8,
                0x81cd, 0x81c7, 0x01c2, 0x0140, 0x8145, 0x814f, 0x014a, 0x815b,
                0x015e, 0x0154, 0x8151, 0x8173, 0x0176, 0x017c, 0x8179, 0x0168,
                0x816d, 0x8167, 0x0162, 0x8123, 0x0126, 0x012c, 0x8129, 0x0138,
                0x813d, 0x8137, 0x0132, 0x0110, 0x8115, 0x811f, 0x011a, 0x810b,
                0x010e, 0x0104, 0x8101, 0x8303, 0x0306, 0x030c, 0x8309, 0x0318,
                0x831d, 0x8317, 0x0312, 0x0330, 0x8335, 0x833f, 0x033a, 0x832b,
                0x032e, 0x0324, 0x8321, 0x0360, 0x8365, 0x836f, 0x036a, 0x837b,
                0x037e, 0x0374, 0x8371, 0x8353, 0x0356, 0x035c, 0x8359, 0x0348,
                0x834d, 0x8347, 0x0342, 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db,
                0x03de, 0x03d4, 0x83d1, 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8,
                0x83ed, 0x83e7, 0x03e2, 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8,
                0x83bd, 0x83b7, 0x03b2, 0x0390, 0x8395, 0x839f, 0x039a, 0x838b,
                0x038e, 0x0384, 0x8381, 0x0280, 0x8285, 0x828f, 0x028a, 0x829b,
                0x029e, 0x0294, 0x8291, 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8,
                0x82ad, 0x82a7, 0x02a2, 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8,
                0x82fd, 0x82f7, 0x02f2, 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb,
                0x02ce, 0x02c4, 0x82c1, 0x8243, 0x0246, 0x024c, 0x8249, 0x0258,
                0x825d, 0x8257, 0x0252, 0x0270, 0x8275, 0x827f, 0x027a, 0x826b,
                0x026e, 0x0264, 0x8261, 0x0220, 0x8225, 0x822f, 0x022a, 0x823b,
                0x023e, 0x0234, 0x8231, 0x8213, 0x0216, 0x021c, 0x8219, 0x0208,
                0x820d, 0x8207, 0x0202};
        int u = 0;
        for (int i = offset; i < offset + len; i++) {
            u = (u << 24 >>> 16) ^ crcTb[(u >>> 8) ^ (data[i] << 24 >>> 24)];
        }
        return u;
    }

    public final static Map<String, Byte> multiWorldVoiceMap = new HashMap<String, Byte>();

    static {
        multiWorldVoiceMap.put("临时车", (byte) 0x12);
        multiWorldVoiceMap.put("月租车", (byte) 0x13);
        multiWorldVoiceMap.put("固定车", (byte) 0xA0);
        multiWorldVoiceMap.put("储值车", (byte) 0x14);
        multiWorldVoiceMap.put("免费车", (byte) 0x16);
        multiWorldVoiceMap.put("贵宾车", (byte) 0x15);
        multiWorldVoiceMap.put("子母车", (byte) 0xA1);
        multiWorldVoiceMap.put("访客车", (byte) 0xA2);
        multiWorldVoiceMap.put("预约车", (byte) 0xA3);
        multiWorldVoiceMap.put("小时", (byte) 0xAF);
        multiWorldVoiceMap.put("分钟", (byte) 0xB0);
        multiWorldVoiceMap.put("天", (byte) 0x31);
    }

    // 单个词查找
    public final static Map<Character, Byte> singleWorldVoiceMap = new HashMap<Character, Byte>();

    static {
        singleWorldVoiceMap.put('点', (byte) 0x27);
        singleWorldVoiceMap.put('十', (byte) 0x28);
        singleWorldVoiceMap.put('百', (byte) 0x29);
        singleWorldVoiceMap.put('千', (byte) 0x2A);
        singleWorldVoiceMap.put('秒', (byte) 0x2D);
        singleWorldVoiceMap.put('分', (byte) 0x2E);
        singleWorldVoiceMap.put('日', (byte) 0x2F);
        singleWorldVoiceMap.put('月', (byte) 0x30);
        singleWorldVoiceMap.put('天', (byte) 0x31);
        singleWorldVoiceMap.put('年', (byte) 0x32);
        singleWorldVoiceMap.put('A', (byte) 0x33);
        singleWorldVoiceMap.put('B', (byte) 0x34);
        singleWorldVoiceMap.put('C', (byte) 0x35);
        singleWorldVoiceMap.put('D', (byte) 0x36);
        singleWorldVoiceMap.put('E', (byte) 0x37);
        singleWorldVoiceMap.put('F', (byte) 0x38);
        singleWorldVoiceMap.put('G', (byte) 0x39);
        singleWorldVoiceMap.put('H', (byte) 0x3A);
        singleWorldVoiceMap.put('I', (byte) 0x3B);
        singleWorldVoiceMap.put('J', (byte) 0x3C);
        singleWorldVoiceMap.put('K', (byte) 0x3D);
        singleWorldVoiceMap.put('L', (byte) 0x3E);
        singleWorldVoiceMap.put('M', (byte) 0x3F);
        singleWorldVoiceMap.put('N', (byte) 0x40);
        singleWorldVoiceMap.put('O', (byte) 0x41);
        singleWorldVoiceMap.put('P', (byte) 0x42);
        singleWorldVoiceMap.put('Q', (byte) 0x43);
        singleWorldVoiceMap.put('R', (byte) 0x44);
        singleWorldVoiceMap.put('S', (byte) 0x45);
        singleWorldVoiceMap.put('T', (byte) 0x46);
        singleWorldVoiceMap.put('U', (byte) 0x47);
        singleWorldVoiceMap.put('V', (byte) 0x48);
        singleWorldVoiceMap.put('W', (byte) 0x49);
        singleWorldVoiceMap.put('X', (byte) 0x4A);
        singleWorldVoiceMap.put('Y', (byte) 0x4B);
        singleWorldVoiceMap.put('Z', (byte) 0x4C);
        singleWorldVoiceMap.put('0', (byte) 0x4D);
        singleWorldVoiceMap.put('1', (byte) 0x4E);
        singleWorldVoiceMap.put('2', (byte) 0x4F);
        singleWorldVoiceMap.put('3', (byte) 0x50);
        singleWorldVoiceMap.put('4', (byte) 0x51);
        singleWorldVoiceMap.put('5', (byte) 0x52);
        singleWorldVoiceMap.put('6', (byte) 0x53);
        singleWorldVoiceMap.put('7', (byte) 0x54);
        singleWorldVoiceMap.put('8', (byte) 0x55);
        singleWorldVoiceMap.put('9', (byte) 0x56);
        singleWorldVoiceMap.put('京', (byte) 0x57);
        singleWorldVoiceMap.put('津', (byte) 0x58);
        singleWorldVoiceMap.put('冀', (byte) 0x59);
        singleWorldVoiceMap.put('晋', (byte) 0x5A);
        singleWorldVoiceMap.put('蒙', (byte) 0x5B);
        singleWorldVoiceMap.put('辽', (byte) 0x5C);
        singleWorldVoiceMap.put('吉', (byte) 0x5D);
        singleWorldVoiceMap.put('黑', (byte) 0x5E);
        singleWorldVoiceMap.put('沪', (byte) 0x5F);
        singleWorldVoiceMap.put('苏', (byte) 0x60);
        singleWorldVoiceMap.put('浙', (byte) 0x61);
        singleWorldVoiceMap.put('皖', (byte) 0x62);
        singleWorldVoiceMap.put('闽', (byte) 0x63);
        singleWorldVoiceMap.put('赣', (byte) 0x64);
        singleWorldVoiceMap.put('鲁', (byte) 0x65);
        singleWorldVoiceMap.put('豫', (byte) 0x66);
        singleWorldVoiceMap.put('鄂', (byte) 0x67);
        singleWorldVoiceMap.put('湘', (byte) 0x68);
        singleWorldVoiceMap.put('粤', (byte) 0x69);
        singleWorldVoiceMap.put('桂', (byte) 0x6A);
        singleWorldVoiceMap.put('琼', (byte) 0x6B);
        singleWorldVoiceMap.put('渝', (byte) 0x6C);
        singleWorldVoiceMap.put('川', (byte) 0x6D);
        singleWorldVoiceMap.put('贵', (byte) 0x6E);
        singleWorldVoiceMap.put('云', (byte) 0x6F);
        singleWorldVoiceMap.put('藏', (byte) 0x70);
        singleWorldVoiceMap.put('陕', (byte) 0x71);
        singleWorldVoiceMap.put('甘', (byte) 0x72);
        singleWorldVoiceMap.put('青', (byte) 0x73);
        singleWorldVoiceMap.put('宁', (byte) 0x74);
        singleWorldVoiceMap.put('新', (byte) 0x75);
        singleWorldVoiceMap.put('港', (byte) 0x76);
        singleWorldVoiceMap.put('澳', (byte) 0x77);
        singleWorldVoiceMap.put('台', (byte) 0x78);
        singleWorldVoiceMap.put('警', (byte) 0x79);
        singleWorldVoiceMap.put('使', (byte) 0x7A);
        singleWorldVoiceMap.put('领', (byte) 0x7C);
        singleWorldVoiceMap.put('学', (byte) 0x7D);
        singleWorldVoiceMap.put('角', (byte) 0x7E);

    }

    // 显示屏清空指令
    public static String getDefault() {
        byte cmd = (byte) 0xD6;
        try {
            byte subCmd = (byte) 0x0;
            byte[] data = packetData(cmd, subCmd, null);
            return byteToHexString2(data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/message")
    public String list2(@RequestBody String Message) {
        System.out.println(Message);
        return "";
    }

    /**
     * 发送行内容（支持广告词模式）
     * @param line        行号（1-4）
     * @param text        显示内容
     * @param displayType 显示方式（0x25:固定显示，0x51:广告词，0x52:临时显示）
     * @return 指令字节数组
     */
    private static byte[] sendLineContent(int line, String text, byte displayType) {
        byte cmd = (byte) 0xD5;
        try {
            byte displayLine = (byte) 0x41; // 显示在第几行
            switch (line) {
                case 1:
                    displayLine = (byte) 0x41;
                    break;
                case 2:
                    displayLine = (byte) 0x42;
                    break;
                case 3:
                    displayLine = (byte) 0x43;
                    break;
                case 4:
                    displayLine = (byte) 0x44;
                    break;
                default:
                    break;
            }
            byte[] cont = text.getBytes("GBK");
            byte[] content = new byte[cont.length + 2];
            content[0] = displayLine;
            content[1] = displayType; // 使用传入的显示方式
            System.arraycopy(cont, 0, content, 2, cont.length);
            return packetData(cmd, (byte) 0x0, content);
        } catch (Exception e) {
            return null;
        }
    }

    public Boolean isEmpty(List<String> deviceIds) {
        if (deviceIds == null || deviceIds.isEmpty()) {
            return true;
        }
        return false;
    }

}

